package vn.gq.tym.view;

import vn.gq.tym.theme.IBackgroundChangeListener;
import vn.gq.tym.truyennguoilonfull.R;
import vn.gq.tym.truyennguoilonfull.ReaderSettings;
import vn.gq.tym.utils.Client;
import vn.gq.tym.utils.DataType;
import vn.gq.tym.utils.IClientListener;
import vn.gq.tym.utils.IScrollListener;
import vn.gq.tym.utils.WebClient;
import vn.gq.tym.widget.BaseFragment;
import android.graphics.Color;
import android.graphics.Picture;
import android.os.Bundle;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.webkit.WebView;
import android.webkit.WebView.PictureListener;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;

@SuppressWarnings("deprecation")
public class WebviewReaderFragment extends BaseFragment implements OnTouchListener, OnClickListener {

	private String mChapterPath;
	private WebView mWebView;
	private int mScrollPosY = 0;
	private ProgressBar mProgressBar;
	private GestureDetectorCompat mDetector;
	private int mPosition;
	private Button mBtnRetry;
	
	public static WebviewReaderFragment newInstance(int position, String filePath, int scrollPos) {
		WebviewReaderFragment f = new WebviewReaderFragment();
		Bundle args = new Bundle();
		args.putString("PATH", filePath);
		args.putInt("SCROLLPOS", scrollPos);
		args.putInt("POSITION", position);
		f.setArguments(args);
		return f;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (getArguments() != null) {
			mChapterPath = getArguments().getString("PATH");
			mScrollPosY = getArguments().getInt("SCROLLPOS");
			mPosition = getArguments().getInt("POSITION");
		}
		setRetainInstance(true);
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
	}

	@Override
	public void onResume() {
		super.onResume();
		if (getActivity() instanceof OnGestureListener && getActivity() instanceof OnDoubleTapListener) {
			mDetector = new GestureDetectorCompat(getActivity(), (OnGestureListener) getActivity());
			mDetector.setOnDoubleTapListener((OnDoubleTapListener) getActivity());
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public int getLayoutId() {
		return R.layout.fragment_reader_webview;
	}

	@Override
	public int getContainerId() {
		return 0;
	}
	
	public void setNightMode() {
		mWebView.setBackgroundColor(Color.BLACK);
		if (getActivity() instanceof IBackgroundChangeListener) {
			((IBackgroundChangeListener) getActivity()).onChangeBackground(Color.BLACK);
		}
	}
	
	public void setLightMode() {
		mWebView.setBackgroundResource(R.color.background_holo_light);
		if (getActivity() instanceof IBackgroundChangeListener) {
			((IBackgroundChangeListener) getActivity()).onChangeBackground(0xfff3f3f3);
		}
	}

	@Override
	public void createView(Bundle savedInstanceState) {
		ReaderSettings settings = ReaderSettings.getInstance(getActivity());
		mBtnRetry = (Button) findViewById(R.id.btn_reconnect);
		mBtnRetry.setOnClickListener(this);
		mWebView = (WebView) findViewById(R.id.webview_reader);
		if (settings.isNightMode()) 
			setNightMode();
		else
			setLightMode();
		
		mWebView.setLongClickable(false);
		mWebView.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View arg0) {
				return true;
			}
		});
		mProgressBar = (ProgressBar) findViewById(R.id.loading);
		mWebView.setOnTouchListener(this);
		if (mScrollPosY < 0) mScrollPosY = 0;
		if (mScrollPosY >= 0) {
			mWebView.setPictureListener(new PictureListener() {
				
				@Override
				@Deprecated
				public void onNewPicture(WebView view, Picture picture) {
					mWebView.scrollTo(0, mScrollPosY);
				}
			});
		}
		
		mWebView.setWebViewClient(new WebViewClient() {

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				mProgressBar.setVisibility(View.GONE);
			}
			
		});
		load();
		int size = settings.getFontSize(0);
		if (size == 0) {
			settings.setFontSize(20);
		} else {
			mWebView.getSettings().setDefaultFontSize(size);
		}
	}
	
	public void load() {
		mProgressBar.setVisibility(View.VISIBLE);
		WebClient client = new WebClient(getActivity());
		client.setOutputDataType(DataType.GZIP_JSON);
		client.executeAndListener(getFilePath(), new IClientListener() {
			
			@Override
			public void onDone(int code, Object result) {
				if (result == null) {
					mBtnRetry.setVisibility(View.VISIBLE);
				} else {
					mBtnRetry.setVisibility(View.GONE);
				}
				mWebView.loadDataWithBaseURL("file:///android_asset/", getHtml(String.valueOf(result)), "text/html", "UTF-8", null);
				mProgressBar.setVisibility(View.GONE);
				mWebView.setVisibility(View.VISIBLE);
			}
		});
	}
	
	public String getHtml(String content) {
		ReaderSettings settings = ReaderSettings.getInstance(getActivity());
		String html = "";
		if (settings.isNightMode()) {
			html = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
					"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML Basic 1.1//EN\" \"http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd\">" +
					"<html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">" +
					"<meta content=\"text/html; charset=UTF-8\" />" +
					"<link rel=\"stylesheet\" type=\"text/css\" href=\"css/dark.css\" />" +
					"</head><body>" + content + "</body></html>";
		} else {
			html = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
					"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML Basic 1.1//EN\" \"http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd\">" +
					"<html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">" +
					"<meta content=\"text/html; charset=UTF-8\" />" +
					"<link rel=\"stylesheet\" type=\"text/css\" href=\"css/light.css\" />" +
					"</head><body>" + content + "</body></html>";
		}
		return html;
	}

	public String getFilePath() {
		if (!mChapterPath.startsWith("http://")) {
			return String.format("asset://gzip:files/%s", mChapterPath);
		}
		return mChapterPath;
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		this.mDetector.onTouchEvent(event);
		mScrollPosY = mWebView.getScrollY();
		if (mScrollPosY < 0) mScrollPosY = 0;
		if (getActivity() instanceof IScrollListener) {
			((IScrollListener) getActivity()).onScroll(mPosition, 0, mScrollPosY);
		}
		return false;
	}
	
	public void onBackPressed() {
		
	}

	@Override
	public void onClick(View v) {
		if (v == mBtnRetry) {
			mBtnRetry.setVisibility(View.GONE);
			load();
		}
	}
	
}
